# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

myStartsWith <- function(str, prefix) {
  substring(str, 1, nchar(prefix)) == prefix
}

library(optparse)
library(ropls)
library(magrittr)
library(RColorBrewer)
library(scales)
library(tidyverse)

option_list <- list(
  make_option("--i", default = "AllMet_with_Anno.csv", type = "character", help = "metabolite data file"),
  make_option("--mc", default = "meta_color.txt", type = "character", help = "metabolite color file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file"),
  make_option("--cp", default = "", type = "character", help = "compare info "),
  make_option("--pc", default = "plot_config.txt", type = "character", help = "config file")

)
opt <- parse_args(OptionParser(option_list = option_list))

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/parse_config.R"))

df <- read_csv("Class_Table_Stat.csv") %>%
  rename(percent = `percent(%)`) %>%
  rowwise() %>%
  do({
    result <- as.data.frame(.)
    percent <- result[1, "percent"]
    class <- result[1, "Class"] %>% as.character()
    newClass <- ifelse(percent < 2, "Others", class)
    result$Class <- newClass
    result
  }) %>%
  group_by(Class) %>%
  summarise_all(sum) %>%
  arrange(desc(percent)) %>%
  mutate(percent = round(percent, 2)) %>%
  mutate(rate = percent / 100, label = str_c(Class, " ", percent, "%"))

df

colorData <- read_tsv(opt$mc) %>%
  select(c("Class", "col")) %>%
  rbind(c("Others", "#0077CC"))

head(colorData)

dfc <- df %>%
  left_join(colorData, by = c("Class"))

opar <- par(no.readonly = TRUE)
charN <- dfc$label %>%
  nchar() %>%
  max
lrM <- charN * 0.03
defaultWidth <- charN * 0.06 + 7

finalWidth <- getFinalWidth(width, defaultWidth, opt$pc)

pdf("Class_Table_Stat_Pieplot.pdf", width = finalWidth, height = height)
par(mar = c(0.5, 0, 0.5, 0) + 0.1, family = "Times")

main <- if (!is.na(mainTitle)) {
  mainTitle
} else ""

pie(dfc$percent, labels = dfc$label, clockwise = TRUE, radius = 0.9, col = dfc$col,
    border = "white", init.angle = 0, main = main)
par(opar)

dev.off()
